<template>
  <a-drawer
    :visible="visible"
    :title="title"
    placement="right"
    :footer-style="{ textAlign: 'center' }"
    width="600"
    @close="cancelClick"
    :destroyOnClose="true"
    :zIndex="9"

  >
    <a-form layout="vertical">
      <a-form-item label="用户名" v-bind="validateInfos.name">
        <a-input
          v-model:value="modelRef.name"
          placeholder="请输入用户名"
          allowClear
        />
      </a-form-item>
      <a-form-item label="用户手机号" v-bind="validateInfos.phone">
        <a-input
          :disabled="id != ''"
          v-model:value="modelRef.phone"
          placeholder="请输入用户手机号"
          @blur="handleBlur"
          allowClear
        />
      </a-form-item>
      <a-form-item label="用户头像" v-bind="validateInfos.avatar">
        <a-upload
          :disabled="userPhoneInfo?.avatar"
          :action="$utils.imgAction"
          :headers="{ 'org-token': $store.getters.token }"
          v-model:file-list="imageList"
          @change="handleLogoUpload"
          name="image"
          :data="{ dir: 'work_ai' }"
          accept="image/*"
          list-type="picture-card"
        >
          <div v-if="!imageList.length">
            <PlusOutlined />
            <div>上传图片</div>
          </div>
        </a-upload>
      </a-form-item>
      <!-- {{ userPhoneInfo?.phone + 'userPhoneInfo?.phone' }} -->
      <a-form-item label="密码" v-bind="validateInfos.password">
        <!-- {{ id + 'id' }} -->
        <a-input
          :disabled="id != '' || (!id && userPhoneInfo?.phone)"
          v-model:value="modelRef.password"
          :placeholder="
            !id ? (userPhoneInfo?.phone ? '******' : '请输入密码') : '******'
          "
          allowClear
        />
        <!-- v-if="!(id != '' || userPhoneInfo?.phone)" -->
        <passwordTips
          v-if="!(id != '' || (!id && userPhoneInfo?.phone))"
          :paddingLeft="0"
          :password="modelRef.password"
        >
        </passwordTips>
      </a-form-item>
      <a-form-item label="角色" v-bind="validateInfos.role">
        <a-select
          ref="select"
          v-model:value="modelRef.role"
          placeholder="请选择角色"
          allowClear
        >
          <a-select-option
            v-for="item in options"
            :value="item.id"
            :key="item.id"
            :disabled="item.status == 0 ? true : false"
          >
            {{ item.name }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="状态" v-bind="validateInfos.status">
        <a-switch
          v-model:checked="modelRef.status"
          checked-children="启用"
          un-checked-children="禁用"
        />
      </a-form-item>
      <a-form-item v-if="visible" label="权限" v-bind="validateInfos.selectedKeys">
        <a-tree
          v-model:selectedKeys="modelRef.selectedKeys"
          :tree-data="treeData"
          v-model:expandedKeys="expandedKeys"
          :defaultExpandAll="false"
        >
          <template #title="slotProps">
            <span> {{ slotProps.title }}</span>
            <span v-if="slotProps.isjuzheng" class="add_ju" @click="open_ju">
              (<span v-if="pingtai_num !== 0"
                >{{ pingtai_num }}个平台{{ zhanghao_num }}个账号，</span
              >点击选择矩阵账号)
            </span>
          </template>
        </a-tree>
      </a-form-item>
    </a-form>
    <template #footer>
      <a-button
        style="
          margin-right: 8px;
          width: 200px;
          border: 1px solid #d9d9d9;
          color: #000;
          border-radius: 5px;
        "
        @click="cancelClick"
        >取消</a-button
      >
      <a-button
        type="primary"
        style="width: 200px; border: none; border-radius: 5px"
        @click="confirmClick"
        :loading="submitLoading"
        >保存</a-button
      >
    </template>

   
  </a-drawer>
  <div class="dw" style="z-index:9999">
      <a-modal
        class="dw_modal"
        centered
        :width="800"
        :maskClosable="false"
        overlayClassName="dw"
        v-model:visible="visible_ju"
        title="选择账号"
        @ok="handleOk"
      >
        <div class="content">
          <a-menu
            style="width: 230px"
            mode="inline"
            v-model:selectedKeys="ju_selectedKeys"
            @click="handleClick"
          >
            <a-menu-item v-for="(item, index) in userList" :key="item.key">
              <img :src="item.image" alt="" class="ju_icon" />
              {{ item.value }}
              <span
                v-if="item.ischecknum !== 0"
                style="
                  height: 100%;
                  border-radius: 5px;
                  margin-right: 3px;
                  background-color: var(--ss-primary-color);
                  color: #fff;
                  padding: 0 5px;
                  margin-left: 5px;
                "
                >{{ item.ischecknum }}</span
              >
            </a-menu-item>
          </a-menu>

          <div class="left_box">
            <div class="all_checkeed">
              <div
                class="left"
                v-show="totalAccounts !== 0 || selectedAccounts !== 0"
              >
                <span v-if="ispower">
                  共有{{ totalAccounts }}个账号，已选择{{
                    selectedAccounts
                  }}个账号
                </span>
                <span v-if="!ispower && selectedAccounts !== 0 && id !== ''">
                  {{ selectedAccounts }}个账号
                </span>

                <span v-if="!ispower && id == ''">
                  共有{{ totalAccounts }}个账号，已选择{{
                    selectedAccounts
                  }}个账号
                </span>
              </div>
              <div class="right" v-if="is_allchecked && !ispower && id == ''">
                <a-checkbox
                  v-model:checked="checkAll"
                  :indeterminate="false"
                  @change="onCheckAllChange"
                >
                  全选
                </a-checkbox>
              </div>
              <div class="right" v-if="is_allchecked && ispower">
                <a-checkbox
                  v-model:checked="checkAll"
                  :indeterminate="false"
                  @change="onCheckAllChange"
                >
                  全选
                </a-checkbox>
              </div>
            </div>
            <div
              v-for="(item, index1) in userList"
              :key="index1"
              style="display: flex; width: 100%; flex-wrap: wrap"
            >
              <div
                v-for="(item2, index2) in item.sub"
                :key="index2"
                style="width: 33%"
              >
                <div v-if="item.key == now_key" class="conetent_item">
                  <div style="display: flex; align-items: center">
                    <a-checkbox
                      v-if="ispower"
                      style="margin-right: 10px"
                      v-model:checked="item2.checked"
                    >
                    </a-checkbox>

                    <a-checkbox
                      v-if="!ispower && id == ''"
                      style="margin-right: 10px"
                      v-model:checked="item2.checked"
                    >
                    </a-checkbox>

                    <img
                      v-if="item2.avatar && ispower "
                      class="ava_img"
                      :src="item2.avatar"
                      alt=""
                    />

                    <div v-if="ispower ">
                      <div class="top">{{ item2.nickname }}</div>
                      <div class="bottom">{{ item2.source_txt }}</div>
                    </div>

                    <img
                      v-if="item2.avatar && !ispower && id == ''"
                      class="ava_img"
                      :src="item2.avatar"
                      alt=""
                    />
                    <div v-if="!ispower && id == ''">
                      <div class="top">{{ item2.nickname }}</div>
                      <div class="bottom">{{ item2.source_txt }}</div>
                    </div>

                    <img
                      v-if="
                        item2.avatar && !ispower && item2.checked && id !== ''
                      "
                      class="ava_img"
                      :src="item2.avatar"
                      alt=""
                    />
                    <div v-if="!ispower && item2.checked && id !== ''">
                      <div class="top">{{ item2.nickname }}</div>
                      <div class="bottom">{{ item2.source_txt }}</div>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <div v-if="!is_allchecked && !userList.length" style="margin-top: 60px">
              <a-empty />
            </div>
          </div>
        </div>

        <template #footer>
          <a-button
            style="
              margin-right: 8px;
              border: 1px solid #d9d9d9;
              color: #000;
              border-radius: 5px;
            "
            @click="handleclose"
            >取消</a-button
          >
          <a-button
            v-if="ispower"
            type="primary"
            style="border: none; border-radius: 5px"
            @click="handleOk"
            >确定</a-button
          >

          <a-button
            v-if="!ispower && id == ''"
            type="primary"
            style="border: none; border-radius: 5px"
            @click="handleOk"
            >确定</a-button
          >
        </template>
      </a-modal>
    </div>
</template>

<script>
import { defineComponent, reactive, toRefs, computed, watch } from "vue";
import { Form } from "ant-design-vue";
import request from "@/common/utils/request";
import routes from "@/router/router.config.js";
import { useRoute, useRouter } from "vue-router";
import { ConfigProvider, message } from "ant-design-vue";
import store from "@/store";
import _ from "lodash";
import { useUpload } from "@/hooks/upload";
import { PlusOutlined } from "@ant-design/icons-vue";

import passwordTips from "@/components/ShotstackLoginModal/component/passwordTips.vue";

import utils from "@/common/utils/utils.js";
const useForm = Form.useForm;

export default defineComponent({
  name: "StaffDrawer",
  components: {
    PlusOutlined,
    passwordTips,
  },
  props: {
    ispower: {
      type: Boolean,
      default: false,
    },
    visible: {
      type: Boolean,
      default: false,
    },
    id: {
      type: [String, Number],
      default: "",
    },
    accountId:{
      type: [String, Number],
      default: "",
    }
  },
  setup(props, { emit }) {
    const route = useRoute();
    const state = reactive({
      loading: false,
      count: 0,
      options: [],
      userPhoneInfo: {},
      submitLoading: false,
      clipRole: [],
      visible_ju: false,
      ju_selectedKeys: [],
      userList: [],
      now_key: "",
      checkAll: false,
      is_allchecked: true,
      expandedKeys: [],
      selectedAccounts: "",
      totalAccounts: "",
      pingtai_num: 0,
      zhanghao_num: 0,
      platformAccountRole: null
    });
    let currentRoutePath = route.path;
    // 不同路由返回对应路由配置文件中的路由配置数据
    let routeName = route.path.includes("workShotstack")
      ? "workShotstack"
      : "SocialMedia";

    // 获取路由列表
    let workShotstack = routes.find((item) => item.name == routeName);

    let workShotstackRoutes = _.cloneDeep(
      workShotstack ? workShotstack.children : []
    );

    const modelRef = reactive({
      name: "",
      password: "",
      role: undefined,
      status: false,
      selectedKeys: [],
      avatar: "",
      phone: "",
    });
    const rulesRef = reactive({
      name: [
        {
          required: true,
          message: "请输入用户名",
        },
        {
          max: 8,
          message: "用户名长度为8个字符以内",
        },
      ],
      password: [
        {
          required: true,
          message: "请输入密码",
        },
        // {
        //   min: 6,
        //   message: "密码不能少于6位",
        // },
        {
          pattern: /^\S*$/,
          message: "密码不能包含空格",
        },
        {
          max: 12,
          message: "密码至多为12位",
        },
      ],
      phone: [
        {
          required: true,
          message: "请输入用户手机号",
        },
      ],
      avatar: [
        {
          required: true,
          message: "请上传头像",
        },
      ],

      role: [
        {
          required: true,
          message: "请选择角色",
        },
      ],
      status: [
        {
          required: false,
        },
      ],
    });

    const { resetFields, validate, validateInfos } = useForm(
      modelRef,
      rulesRef
    );
    let { imageList, handleUpload: handleLogoUpload } = useUpload();
    const cancelClick = () => {
      resetFields();
      // imageList.value = [];
      // state.userList = [];
      // state.ju_selectedKeys = [];
      // state.zhanghao_num = 0;
      // state.pingtai_num = 0;
      emit("onCancel");
    };

    const handleBlur = (e) => {
      if (e.target.value?.length === 11) {
        request
          .get("user", "/user/phone", {
            phone: e.target.value,
            phone_country: "86",
          })
          .then((res) => {
            if (res?.result?.phone) {
              state.userPhoneInfo = res.result;
              modelRef.name = res?.result?.nickname;
              if (res.result.avatar) {
                imageList.value = [
                  {
                    url: res.result.avatar,
                    name: "avatar",
                    status: "done",
                  },
                ];
              } else {
                imageList.value = [
                  {
                    url: modelRef.avatar,
                    name: "avatar",
                    status: "done",
                  },
                ];
              }
              // modelRef.avatar = res.result?.avatar || [];
              modelRef.password = "";
              rulesRef.password[0].required = false;
            } else {
              state.userPhoneInfo = "";
              // modelRef.name = ''
              // imageList.value = []
              // resetFields()
              // state.userPhoneInfo = {};
              // modelRef.avatar = "";
              // modelRef.password = "";
              // rulesRef.avatar[0].required = true;
              // rulesRef.password[0].required = true;
            }
          })
          .catch(() => {
            // state.userPhoneInfo = {};
            // modelRef.avatar = "";
            // modelRef.password = "";
            // rulesRef.avatar[0].required = true;
            // rulesRef.password[0].required = true;
          });
      } else {
        if (state.userPhoneInfo.phone) {
          modelRef.avatar = "";
          modelRef.password = "";
        }
        state.userPhoneInfo = {};
        rulesRef.avatar[0].required = true;
        rulesRef.password[0].required = true;
      }
    };

    const confirmClick = () => {
      validate().then(() => {
        state.submitLoading = true;
        addStaff();
      });
    };

    const title = computed(() => {
      return props.id ? "编辑员工" : "添加员工";
    });

    const addStaff = () => {
      let data = state.userList.reduce((acc, v1) => {
        if (v1.sub && Array.isArray(v1.sub)) {
          acc[v1.key] = acc[v1.key] || [];

          v1.sub.forEach((v2) => {
            if (v2.checked) {
              acc[v1.key].push(v2.id);
            }
          });
        }
        return acc;
      }, {});
      let url = "/user/team/user/add";
      let method = "post";
      let params = {
        status: modelRef.status ? 1 : 0,
        nickname: modelRef.name,
        team_id: store.state.user.teamId,
        phone: modelRef.phone,
        role_id: modelRef.role,
        password: modelRef.password,
        avatar: modelRef.avatar,
        platform_account_role: data,
      };
      if(state.platformAccountRole && Object.keys(state.platformAccountRole).length){
        params.platform_account_role = state.platformAccountRole
      }
      if (state.userPhoneInfo?.phone) {
        delete params.password;
      }
      if (props.id) {
        params.id = props.id;
        url = "/user/team/user/update";
        method = "put";
        delete params.password;
      }

      request[method]("/work_ai", url, params)
        .then((res) => {
          state.userPhoneInfo = {};
          message.success("操作成功");
          emit("onConfirm");
          state.submitLoading = false;
          imageList.value = [];
          state.userList = [];
          state.ju_selectedKeys = [];
          state.zhanghao_num = 0;
          state.pingtai_num = 0;
          resetFields();
        })
        .catch(() => {
          state.submitLoading = false;
          state.userPhoneInfo = {};
        });
    };

    const getDetail = () => {
      state.loading = true;
      request
        .get("/work_ai", "/user/team/user/get", {
          id: props.id || props.accountId,
        })
        .then((res) => {
          if (res?.result?.user) {
            modelRef.name = res.result.nickname;
            modelRef.phone = res.result.user.phone;
            modelRef.role = res.result.role_id;
            modelRef.avatar = res.result.avatar;
            if (modelRef.avatar) {
              imageList.value = [
                {
                  url: modelRef.avatar,
                  name: "avatar",
                  status: "done",
                },
              ];
            }

            modelRef.status = res.result.status == 1 ? true : false;
          }
          state.platformAccountRole = res.result.platform_account_role

          state.pingtai_num = 0;
          state.zhanghao_num = 0;

          Object.entries(res.result.platform_account_role).forEach(
            ([platform, ids]) => {
              if (ids && ids.length > 0) {
                state.pingtai_num++;
                state.zhanghao_num += ids.length;
              }
            }
          );
         
          state.loading = false;
        });
    };
    watch(
      () => props.visible,
      (visible) => {
        visible && getOptions();
        if (visible && props.id) {
          getDetail();
        } else {
          imageList.value = [
            {
              uid: "avatar",
              url:
                utils.staticPath +
                "images/workAi/shotstack/user_head_portrait.png",
              name: "avatar.png",
              status: "done",
            },
          ];
        }
      }
    );
    const getOptions = () => {
      request.get("/work_ai", "/user/team/role/list", {}).then((res) => {
        state.options = res.result;
      });
    };
    getOptions();

    let getFilterHideRoutes = (menuItems) => {
      return menuItems.filter((menu) => {
        // 如果当前菜单项被隐藏，则返回 false
        if (menu.meta.hidden) {
          return false;
        }

        // 如果有子菜单项，递归过滤子菜单项
        if (menu.children && menu.children.length > 0) {
          menu.children = getFilterHideRoutes(menu.children);
        }

        // 返回 true，表示当前菜单项是可见的
        return true;
      });
    };
    // 获取过滤hidden的路由列表
    let filterHideRoutes = getFilterHideRoutes(workShotstackRoutes);

    filterHideRoutes.forEach((item) => {
      if (item.name === "CreationCenter") {
        item.children?.forEach((it) => {
          if (it.name === "IntelligentClipping") {
            it.children = [
              {
                name: "znjj",
                disabled: !state.clipRole.includes("znjj"),
                meta: {
                  title: "智能剪辑",
                },
              },
              {
                name: "yjcp",
                disabled: !state.clipRole.includes("yjcp"),
                meta: {
                  title: "一键成片",
                },
              },
              {
                name: "ksjj",
                disabled: !state.clipRole.includes("ksjj"),
                meta: {
                  title: "模板剪辑",
                },
              },
              {
                name: "jbjj",
                disabled: !state.clipRole.includes("jbjj"),
                meta: {
                  title: "脚本剪辑",
                },
              },
              {
                name: "twjj",
                disabled: !state.clipRole.includes("twjj"),
                meta: {
                  title: "图文剪辑",
                },
              },
            ];
          }
          if (it.name === "CreativityTools") {
            it.children = [
              {
                name: "wzzyy",
                disabled: !state.clipRole.includes("wzzyy"),
                meta: {
                  title: "文字转语音",
                },
              },
              {
                name: "aicz",
                disabled: !state.clipRole.includes("aicz"),
                meta: {
                  title: "AI创作",
                },
              },
              {
                name: "spzncf",
                disabled: !state.clipRole.includes("spzncf"),
                meta: {
                  title: "视频智能拆分",
                },
              },
              {
                name: "tqspwz",
                disabled: !state.clipRole.includes("tqspwz"),
                meta: {
                  title: "提取视频文字",
                },
              },
            ];
          }
        });
      }
    });

    // 通过权限key获取对应的菜单列表
    const createRolePermission = (permission_ids) => {
      return filterRolePermission(
        _.cloneDeep(filterHideRoutes),
        permission_ids
      );
    };

    // 格式化路由tree
    const formatTree = (data) => {
      return data.map((item) => {
        return {
          key: item.name,
          title: item.meta.title,
          children:
            item.children && item.children.length
              ? formatTree(item.children)
              : [],
        };
      });
    };

    // //  递归  循环
    const filterRolePermission = (allMenus, permission_ids) => {
      return allMenus.filter((menu) => {
        const hasPermissionOnThisLevel = permission_ids.includes(menu.name);
        if (menu.children) {
          // 递归过滤子菜单，并更新当前菜单的 children
          menu.children = filterRolePermission(menu.children, permission_ids);
          // 当前菜单至少有一个子菜单项或者自身就在权限列表内时，返回 true
          return menu.children.length > 0 || hasPermissionOnThisLevel;
        } else {
          // 如果没有子菜单，则直接检查当前菜单项是否在权限列表内
          return hasPermissionOnThisLevel;
        }
      });
    };

    // 拉去数的数据
    const treeData = computed(() => {
      let role = state.options.find((item) => item.id == modelRef.role);

      let permissions = role?.data ?? [];
      let menus = createRolePermission(permissions);

      permissions.forEach((item) => {
        if (item === "myTemplate") {
          const materialCenterItem = menus.find(
            (v1) => v1.name === "MaterialCenter"
          );
          if (!materialCenterItem) {
            menus.push({
              meta: {
                title: "创意素材",
                permission: ["admin"],
              },
              children: [
                {
                  meta: {
                    title: "模版广场",
                  },
                  name: "mbgc",
                  path: "mbgc",
                  children: [
                    {
                      meta: {
                        title: "我的模版",
                      },
                      name: "myTemplate",
                      path: "myTemplate",
                    },
                  ],
                },
              ],
            });
          }

          if (materialCenterItem) {
            const templateListItem = materialCenterItem.children.find(
              (v2) => v2.name === "TemplateList"
            );

            if (templateListItem) {
              if (!templateListItem.children) {
                templateListItem.children = [];
              }
              templateListItem.children.push({
                meta: {
                  title: "我的模版",
                },
                name: "myTemplate",
                path: "myTemplate",
              });
            }
          }
        } else if (item === "mbgc") {
          const materialCenterItem = menus.find(
            (v1) => v1.name === "MaterialCenter"
          );

          if (!materialCenterItem) {
            menus.push({
              meta: {
                title: "创意素材",
                permission: ["admin"],
              },
              children: [
                {
                  meta: {
                    title: "模版广场",
                  },
                  name: "mbgcF",
                  path: "mbgcF",
                  children: [
                    {
                      meta: {
                        title: "模版广场",
                      },
                      name: "mbgc",
                      path: "mbgc",
                    },
                  ],
                },
              ],
            });
          } else {
            const templateListItem = materialCenterItem.children.find(
              (v2) => v2.name === "TemplateList"
            );

            if (templateListItem) {
              if (!templateListItem.children) {
                templateListItem.children = [];
              }
              templateListItem.children.push({
                meta: {
                  title: "模版广场",
                },
                name: "mbgc",
                path: "mbgc",
              });
            } else {
              materialCenterItem.children.push({
                name: "TemplateList",
                children: [
                  {
                    meta: {
                      title: "模版广场",
                    },
                    name: "mbgc",
                    path: "mbgc",
                  },
                ],
              });
            }
          }
        }
      });

      let tree = formatTree(menus);

      function moveCommentMessageToTop(tree) {
        for (let i = 0; i < tree.length; i++) {
          if (
            tree[i].key === "MatrixMarketing" &&
            Array.isArray(tree[i].children)
          ) {
            for (let j = 0; j < tree[i].children.length; j++) {
              if (tree[i].children[j].key === "CommentMessage") {
                const commentMessageNode = tree[i].children.splice(j, 1)[0];

                if (tree.length > 1) {
                  tree.splice(tree.length - 1, 0, commentMessageNode);
                } else {
                  tree.push(commentMessageNode);
                }

                return;
              }
            }
          }
        }
      }

      // 使用方法：
      moveCommentMessageToTop(tree);
      tree.forEach((v1) => {
        if (v1.key == "MatrixMarketing" && v1.children.length > 0) {
          v1.children.forEach((v2) => {
            if (v2.key == "IpManage") {
              v2.isjuzheng = true;
            }
          });
        }
      });

      state.expandedKeys = ["MatrixMarketing"];
      return tree;
    });

    watch(
      imageList,
      (list) => {
        if (list.length) {
          modelRef.avatar = list[0].url;
        } else {
          modelRef.avatar = "";
        }
      },
      {
        deep: true,
        immediate: true,
      }
    );
    watch(
      () => props.id,
      (id) => {
        if (id) {
          rulesRef.password[0].required = false;
        } else {
          rulesRef.password[0].required = true;
        }
      },
      {
        deep: true,
        immediate: true,
      }
    );

    const open_ju = () => {
      state.visible_ju = true;
      if (state.userList.length == 0) {
        if (props.id || props.accountId) {
          request
            .get("/work_ai", "/org/platform/account/shotStackList", {
              powerFilter: 1,
            })
            .then((res) => {
              // 更新 userList 并初始化 sub 的 checked 状态
              state.userList = res.result.map((item) => ({
                ...item,
                isallchecked: false,
                ischecknum: 0,
                sub: item.sub
                  ? item.sub.map((subItem) => ({
                      ...subItem,
                      checked: false,
                    }))
                  : undefined,
              }));
              state.ju_selectedKeys.push(state.userList[0].key);
              state.now_key = state.userList[0].key;

              if (props.id || props.accountId) {
                request
                  .get("/work_ai", "/user/team/user/get", {
                    id: props.id,
                  })
                  .then((res) => {
                    if (res?.result?.user) {
                      modelRef.name = res.result.nickname;
                      modelRef.phone = res.result.user.phone;
                      modelRef.role = res.result.role_id;
                      modelRef.avatar = res.result.avatar;
                      if (modelRef.avatar) {
                        imageList.value = [
                          {
                            url: modelRef.avatar,
                            name: "avatar",
                            status: "done",
                          },
                        ];
                      }

                      modelRef.status = res.result.status == 1 ? true : false;
                    }

                    state.platformAccountRole = res.result.platform_account_role

                    const platformRoles = res.result.platform_account_role;

                    state.userList.forEach((item) => {
                      if (Object.keys(platformRoles).includes(item.key)) {
                        const roleIds = platformRoles[item.key];
                        let checkedCount = 0;

                        item.sub.forEach((subItem) => {
                          subItem.checked = roleIds.includes(subItem.id);
                          if (subItem.checked) {
                            checkedCount++;
                          }
                        });

                        item.ischecknum = checkedCount;
                        item.isallchecked =
                          item.sub &&
                          item.sub.every((subItem) => subItem.checked);
                        if (!props.ispower) {
                          item.sub = item.sub
                            ? item.sub.filter((subItem) => subItem.checked)
                            : undefined;
                        }
                      }
                    });
                  });
              }

              state.checkAll = state.userList[0].isallchecked;
              if (state.userList.length == 0) {
                state.is_allchecked = false;
              }
            });
        } else {
          request
            .get("/work_ai", "/org/platform/account/shotStackList")
            .then((res) => {
              // 更新 userList 并初始化 sub 的 checked 状态
              state.userList = res.result.map((item) => ({
                ...item,
                isallchecked: false,
                ischecknum: 0,
                sub: item.sub
                  ? item.sub.map((subItem) => ({
                      ...subItem,
                      checked: false,
                    }))
                  : undefined,
              }));
              state.ju_selectedKeys.push(state.userList[0].key);
              state.now_key = state.userList[0].key;
              state.checkAll = state.userList[0].isallchecked;
              if (state.userList.length == 0) {
                state.is_allchecked = false;
              }
            });
        }

        if (state.userList.length == 0 && !props.ispower) {
          state.is_allchecked = false;
        }
      }
    };

    const handleClick = (e) => {
      state.now_key = e.key;
      const item = state.userList.find((item) => item.key === e.key);
      if (item) {
        state.checkAll = item.isallchecked;
        state.totalAccounts = item.sub.length;
        state.selectedAccounts = item.sub.filter(
          (subItem) => subItem.checked
        ).length;
      }

      let hasEmptySub = state.userList.some(
        (item) => item.key === e.key && item.sub.length === 0
      );

      if (!props.ispower && props.id !== "") {
        state.userList.forEach((item) => {
          if (item.key === e.key) {
            const allSubCheckedFalse = item.sub
              ? item.sub.every((subItem) => !subItem.checked)
              : true;
            if (allSubCheckedFalse) {
              hasEmptySub = true;
            } else {
            }
          }
        });
      }

      state.is_allchecked = !hasEmptySub;
    };

    const onCheckAllChange = () => {
      state.userList.forEach((item) => {
        if (item.key == state.now_key) {
          if (item.isallchecked) {
            if (item.sub) {
              item.sub.forEach((subItem) => {
                subItem.checked = false;
              });
              item.isallchecked = false;
            }
          } else {
            if (item.sub) {
              item.sub.forEach((subItem) => {
                subItem.checked = true;
              });
              item.isallchecked = true;
            }
          }
        }
      });
    };

    const handleOk = () => {
      state.visible_ju = false;
      state.platformAccountRole =  null
      state.zhanghao_num = 0;
      state.pingtai_num = 0;
      state.userList.forEach((item) => {
        if (item.sub && Array.isArray(item.sub)) {
          const checkedSubItemsCount = item.sub.filter(
            (subItem) => subItem.checked
          ).length;
          state.zhanghao_num += checkedSubItemsCount;
          if (checkedSubItemsCount > 0) {
            state.pingtai_num++;
          }
        }
      });
      if(props.accountId){
        addStaff()
        emit('onAccountChange')
      }
      
    };

    const handleclose = () => {
      state.visible_ju = false;
      emit('onAccountCancel')
    };

    watch(
      () => state.userList,
      (newVal) => {
        if (newVal.length) {
          newVal.forEach((item) => {
            if (item.key === state.now_key && item.sub) {
              state.totalAccounts = item.sub.length;
              state.selectedAccounts = item.sub.filter(
                (subItem) => subItem.checked
              ).length;

              const allChecked = item.sub.every((subItem) => subItem.checked);
              state.checkAll = allChecked;

              const checkedSubItems = item.sub.filter(
                (subItem) => subItem.checked
              );
              item.ischecknum = checkedSubItems.length;
            }
          });
        }
      },
      {
        deep: true,
        immediate: true,
      }
    );

    watch(
      ()=>props.accountId,
      (val)=>{
        if(val){
          state.userList =[]
          open_ju()
        }else{
          state.visible_ju = false;
        }
      }
    )

    return {
      ...toRefs(state),
      title,
      cancelClick,
      confirmClick,
      validateInfos,
      resetFields,
      modelRef,
      treeData,
      handleLogoUpload,
      imageList,
      rulesRef,
      validateInfos,
      handleBlur,
      open_ju,
      handleClick,
      onCheckAllChange,
      handleOk,
      handleclose,
    };
  },
});
</script>

<style lang="less">
.dw_modal {
  .ss-modal-body {
    padding: 0 !important;
  }
}

.ss-menu-item {
  height: 55px !important;
  line-height: 40px;
  padding: 8px 0 8px 24px !important;
  display: flex;
  align-items: center;
  margin: 0px !important;
  transition: border-color 0.3s, background 0.3s,
    padding 0.1s cubic-bezier(0.215, 0.61, 0.355, 1);
}

.ss-menu-item-selected {
  background-color: #f0f8ff !important;
}
</style>

<style lang="less" scoped>
.add_ju {
  cursor: pointer;
  margin-left: 20px;
}

.ju_icon {
  width: 40px;
  height: 40px;
  border-radius: 5px;
  margin-right: 5px;
}

.content {
  display: flex;
}
.left_box {
  width: 100%;
  max-height: 300px;
  overflow-y: auto;
  padding: 15px;
}

.conetent_item {
  display: flex;
  margin-bottom: 20px;
}

.all_checkeed {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-right: 10px;
  margin-bottom: 20px;
}

.ava_img {
  height: 35px;
  width: 35px;
  border-radius: 35px;
  margin-right: 10px;
}

.bottom {
  font-size: 12px;
  color: #ccc;
}

.top {
  width: 100px;
    white-space: nowrap;         
  overflow: hidden;           
  text-overflow: ellipsis; 
}
</style>
